package httputils

import (
	"dyhttp/dbutil"
	"encoding/json"
	"fmt"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
)

type HttpGui struct {
	service        *HttpService
	Win            fyne.Window
	SendType       bool
	SendTypeUI     *widget.Check
	Format         *widget.Check
	Input          *widget.Entry
	Output         *widget.Entry
	ContentType    *widget.Select
	Url            *widget.Entry
	Method         *widget.Select
	Cookie         *widget.Entry
	Header         *widget.Entry
	ExecStart      *widget.Entry
	ExecEnd        *widget.Entry
	ForStatus      *widget.Check
	ForSize        *widget.Entry
	SleepSize      *widget.Entry
	send           *widget.Button
	save           *widget.Button
	change         *widget.Button
	delete         *widget.Button
	OldSelect      *widget.SelectEntry
	OldSelectValue string
}

func NewHttpGui(win fyne.Window) fyne.CanvasObject {
	gui := new(HttpGui)
	gui.Win = win
	gui.Input = widget.NewMultiLineEntry()
	gui.Output = widget.NewMultiLineEntry()
	gui.Output.Hide()
	gui.service = NewHttpService(gui)
	return container.NewBorder(gui.TopContent(), nil, nil, gui.NewHttpToolbar(), gui.Input, container.NewScroll(gui.Output))
}

func (m *HttpGui) TopContent() fyne.CanvasObject {
	m.ContentType = widget.NewSelect([]string{"application/json", "application/x-www-form-urlencoded", "multipart/form-data", "text/xml", "text/html"}, func(s string) {
	})
	m.ContentType.SetSelectedIndex(0)
	m.Method = widget.NewSelect([]string{"POST", "GET", "PUT", "DELETE"}, func(s string) {
	})
	m.Method.SetSelectedIndex(0)
	m.Url = widget.NewEntry()
	m.Header = widget.NewEntry()
	m.Header.PlaceHolder = `key=value;`
	m.Cookie = widget.NewEntry()

	return container.NewVBox(
		widget.NewForm(widget.NewFormItem("请求地址", m.Url)),
		container.NewGridWithColumns(4,
			widget.NewForm(widget.NewFormItem("请求方式", m.ContentType)),
			widget.NewForm(widget.NewFormItem("数据类型", m.Method)),
			widget.NewForm(widget.NewFormItem("Cookie", m.Cookie)),
			widget.NewForm(widget.NewFormItem("Header", m.Header)),
		),
	)
}

func (m *HttpGui) NewHttpToolbar() fyne.CanvasObject {
	m.OldSelect = widget.NewSelectEntry([]string{})
	m.OldSelect.OnChanged = func(s string) {
		m.OldSelectValue = s
		bs := dbutil.Get(m.OldSelectValue)
		if len(bs) > 1 {
			data := HttpData{}
			json.Unmarshal(bs, &data)
			m.service.bindData(&data)
		}
	}
	m.bindSelect()
	dyValueData := make(map[string]string, 0)
	dyValueData["随机数"] = "int:9"
	dyValueData["随机串"] = "str:32"
	dyValueData["请求取值"] = "req:0:name"
	dyValueData["响应取值"] = "res:0:name"
	dyValueData["2006-01-02 15:04:05"] = "date:2006-01-02 15:04:05"
	dyValueData["2006-01-02"] = "date:2006-01-02"
	dyValueData["timestamp"] = "date:timestamp"
	dyValueData["结束符"] = "-END-"
	dyValueData["原始报文"] = "data = {};"
	dyValueData["文件上传"] = "uploadName = filePath = "
	titles := make([]string, 0)
	for k := range dyValueData {
		titles = append(titles, k)
	}

	showDyValue := widget.NewEntry()
	dyValueSelect := widget.NewSelect(titles, func(s string) {
		showDyValue.SetText(dyValueData[s])
	})
	dyValueSelect.PlaceHolder = "内置参数"
	m.ExecStart = widget.NewEntry()
	m.ExecStart.SetText("1")
	m.ExecEnd = widget.NewEntry()
	m.ExecEnd.SetText("99")
	m.ExecEnd.Resize(fyne.NewSize(36, 200))

	m.ForSize = widget.NewEntry()
	m.ForSize.SetText("200")
	m.SleepSize = widget.NewEntry()
	m.SleepSize.SetText("500")
	m.SleepSize.Resize(fyne.NewSize(0, 2000))

	m.Format = widget.NewCheck("格式化", func(b bool) {

	})
	m.Format.SetChecked(true)
	m.send = widget.NewButton("发送", func() {
		m.Output.SetText("")
		m.service.ExecSendHttp()
	})

	m.change = widget.NewButton("切换", func() {
		if m.Input.Hidden {
			m.Input.Show()
		} else {
			m.Input.Hide()
		}
		if m.Output.Hidden {
			m.Output.Show()
		} else {
			m.Output.Hide()
		}
	})
	m.save = widget.NewButton("保存", func() {
		data := m.service.readData()
		dbutil.Write(data.Name, data)
		m.bindSelect()
	})
	m.delete = widget.NewButton("删除", func() {
		key := m.OldSelectValue
		dbutil.Delete(key)
		m.bindSelect()
	})
	m.ForStatus = widget.NewCheck("循环", func(b bool) {
		if b {
			m.ForSize.Enable()
			m.SleepSize.Enable()
		} else {
			m.ForSize.Disable()
			m.SleepSize.Disable()
		}
	})
	m.ForStatus.SetChecked(false)
	m.ForSize.Disable()
	m.SleepSize.Disable()
	m.SendTypeUI = widget.NewCheck("原始", func(b bool) {
		m.SendType = b
	})
	m.SendType = false
	m.SendTypeUI.SetChecked(m.SendType)

	return container.NewVBox(
		m.OldSelect,
		m.SendTypeUI,
		widget.NewForm(
			widget.NewFormItem("执行:", container.NewGridWithColumns(3, m.ExecStart, m.ExecEnd, m.Format)),
		),
		widget.NewForm(
			widget.NewFormItem("内置:", container.NewGridWithColumns(2, dyValueSelect, showDyValue)),
		),
		widget.NewForm(
			widget.NewFormItem("压测:", container.NewGridWithColumns(3, m.ForSize, m.SleepSize, m.ForStatus)),
		),
		container.NewGridWithColumns(1, m.send, m.change, m.save, m.delete),
	)
}

func (m *HttpGui) bindSelect() {
	key := m.OldSelectValue
	datas := dbutil.ReadAll[HttpData]()
	fmt.Println(datas)
	options := make([]string, 0)
	for _, v := range datas {
		options = append(options, v.Name)
	}
	m.OldSelect.SetOptions(options)
	for _, d := range datas {
		if d.Name == key {
			m.OldSelect.SetText(key)
			break
		}
	}
}
